//
//  loginViewController.m
//  ttsdktestapp
//
//  Created by wangna on 14-12-24.
//  Copyright (c) 2014年 wangna. All rights reserved.
//

#import "loginViewController.h"
//#import "ttsdkAppDelegate.h"
//#import "createGroupViewController.h"
//#import "chattingViewController.h"
#import "WoaOpenApi.h"
#import "chattingViewController.h"

#define kAppId 204292500
#define URL_TEST @"https://auth.app.tt.gameabc.com:8098/reg/accountreg"

@interface LoginViewController ()<woaDelegate>

{
    
}
@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)initWoaAPI
{
   WoaOpenApi * _woaOpenAPI = [WoaOpenApi shareWoaOpenAPI];
    if (![_woaOpenAPI isInit]) {
        _woaOpenAPI.appId = kAppId;
        _woaOpenAPI.areaId = 1;
        [_woaOpenAPI setLocationServiceEnable:NO];
        [_woaOpenAPI setDelegate:self];
        [_woaOpenAPI woaInit];
    }
}
-(void)loadshortid:(NSString *)ssid
{
    NSDictionary *args = @{@"sysver":[UIDevice currentDevice].systemVersion,@"clientver":@"3.0",@"account_data":@{@"sid":ssid},@"did":@"865072026881139",@"devmodel":[UIDevice currentDevice].model,@"chid":@"X10001",@"sysid":@0,@"password":@"",@"account_type":@2};
    
    NSString *url = [NSString stringWithFormat:@"%@",URL_TEST];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5];
    [request setHTTPMethod:@"POST"];
    NSError *error = nil;
    [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:args options:NSJSONWritingPrettyPrinted error:&error]];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [conn start];
//    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        NSLog(@"%@ response %@",connectionError,[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//        
//    } ];
    
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection{
    
    return NO;
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{
    NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"response %@",response);
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    NSString *imid = [dic objectForKey:@"imid"];
    NSString *token = [dic objectForKey:@"token"];
} 



//下面两段是重点，要服务器端单项HTTPS 验证，iOS 客户端忽略证书验证。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    
    NSLog(@"didReceiveAuthenticationChallenge %@ %zd", [[challenge protectionSpace] authenticationMethod], (ssize_t) [challenge previousFailureCount]);
    
    
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
        
        [[challenge sender]  useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        
        [[challenge sender]  continueWithoutCredentialForAuthenticationChallenge: challenge];
        
    }
    
}



//[receivedData setLength:0];

//处

- (void)onSuccess:(eOptType)optType result:(NSDictionary*)paraDic
{
    NSLog(@"success %@",paraDic);
    if (optType == eLogin) {
        [self loadshortid:[WoaOpenApi shareWoaOpenAPI].getSessionId];
//        ChattingViewController *controller = [[ChattingViewController alloc] initWithNibName:@"chattingViewController" bundle:nil];
//        [self.navigationController pushViewController:controller animated:YES];
    }
}

- (void)onFail:(eOptType)optType result:(NSDictionary*)paraDic
{
    NSLog(@"fail %@",paraDic);
    
    
}


- (void)viewDidLoad
{
    [self initWoaAPI];
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    _loginResult.text = @"";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//-(IBAction)loginAction:(id)sender
//{
//    NSString *phone = nameField.text;
//    NSString *pwd = pwdField.text;
//    [[WoaOpenApi shareWoaOpenAPI] setDelegate:self];
//    [[WoaOpenApi shareWoaOpenAPI] loginByPT:phone password:pwd];
//}

- (IBAction)login:(id)sender {
    
//    ttsdkAppDelegate *delegate = (ttsdkAppDelegate *)[UIApplication sharedApplication].delegate;
//    [delegate.app connect];
    _loginResult.text = @"正在登陆";
    NSString *phone = nameField.text;
    NSString *pwd = pwdField.text;
    [[WoaOpenApi shareWoaOpenAPI] setDelegate:self];
    [[WoaOpenApi shareWoaOpenAPI] loginByPT:phone password:pwd];

}

- (void) onConnect:(int32_t)result
{
    NSString * strResult = [NSString stringWithFormat:@"connect result:%d", result];
    _loginResult.text = strResult;
}

- (void) onLogin:(int32_t)result
{
    if(result == 0)
    {
        // 显示创建群的界面
//        dispatch_async(dispatch_get_main_queue(), ^{
//            CreateGroupViewController * createGroupViewController = [[CreateGroupViewController alloc] initWithNibName:@"createGroupViewController" bundle:nil];
//            
//            ttsdkAppDelegate *delegate = (ttsdkAppDelegate *)[UIApplication sharedApplication].delegate;
//            //设置委托
//            [delegate.app.sdk_connect setDelegate:createGroupViewController];
//            //显示界面
//            delegate.window.rootViewController = createGroupViewController;
//        });
    }
    else
    {
        NSString * strResult = [NSString stringWithFormat:@"login:%d", result];
        _loginResult.text = strResult;
    }
}


@end
